package com.winit.cloudlink.message.monitor;

import com.google.common.collect.Maps;
import com.winit.cloudlink.common.URL;
import com.winit.cloudlink.config.Metadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Monitor {
	private static final Logger logger = LoggerFactory.getLogger(Monitor.class);
	public static final Monitor INSTANCE = new Monitor();
	public final Map<Class, String> messages = Maps.newConcurrentMap();
	private Alerter alerter = null;

	private Monitor() {
		final ScheduledExecutorService service = Executors
				.newSingleThreadScheduledExecutor();
		service.scheduleAtFixedRate(new AlerterRunner(), 10, 60 * 10, TimeUnit.SECONDS); // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				service.shutdownNow();
			}
		});
	}

	public static Monitor getInstance() {
		return INSTANCE;
	}

	public void init(Metadata metadata) {
		URL alertUrl = metadata.getApplicationOptions().getAlertUrl();
		this.alerter = alertUrl == null ?
				new UpushAlerter() : new UpushAlerter(alertUrl);
	}

	public void alert(Throwable throwable) {
		if (!messages.containsKey(throwable.getClass())) {
			messages.put(throwable.getClass(), throwable.getMessage());
		}
	}

	private class AlerterRunner implements Runnable {
		public void run() {
			for (Map.Entry<Class, String> entry : messages.entrySet()) {
				sendAlert(entry.getValue());
				messages.remove(entry.getKey());
			}
		}

		private void sendAlert(String message) {
			if (alerter == null) {
				return;
			}
			try {
				alerter.alert(message);
			} catch (Exception e) {
				logger.error("发告警失败.", e);
			}
		}
	}


}
